from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select


class BasePage(object):

    def __init__(self, driver: webdriver):
        self.driver = driver

    # 打开页面并最大化
    def open_page_and_max(self, url):
        self.driver.get(url)
        self.driver.maximize_window()

    # 刷新页面
    def refresh_page(self):
        self.driver.refresh()

    # 定位元素+等待
    def find_el(self, loc):
        el = WebDriverWait(self.driver, 10, 0.5).until(EC.presence_of_element_located(loc))
        return el

    # 定位元素s+等待
    def find_els(self, loc):
        els = WebDriverWait(self.driver, 10, 0.5).until(EC.presence_of_all_elements_located(loc))
        return els

    # 定位元素+清除输入再输入
    def send_keys_to_el(self, loc, content):
        el = self.find_el(loc)
        el.clear()
        el.send_keys(content)

    # 定位元素+点击
    def click_to_el(self, loc):
        self.find_el(loc).click()

    # 使用JavaScript获取元素的字体、字体大小
    def get_el_font(self, loc):
        font = {}
        script_font = "return window.getComputedStyle(arguments[0], null).getPropertyValue('font-family');"
        script_font_size = "return window.getComputedStyle(arguments[0], null).getPropertyValue('font-size');"
        script_font_color = "return window.getComputedStyle(arguments[0], null).getPropertyValue('color');"
        font['family'] = self.driver.execute_script(script_font, self.find_el(loc))
        font['size'] = self.driver.execute_script(script_font_size, self.find_el(loc))
        font['color'] = self.driver.execute_script(script_font_color, self.find_el(loc))
        return font

    # 获取页面url
    def get_page_url(self):
        return self.driver.current_url

    # 查询页面localStorage项并返回
    def get_local_storage(self, condition):
        script = 'return localStorage.getItem("{}")'.format(condition)
        return self.driver.execute_script(script)

    # 查询页面sessionStorage项并返回
    def get_session_storage(self, condition):
        script = 'return sessionStorage.getItem({})'.format(condition)
        return self.driver.execute_script(script)

    # 等待一个alert并获取alert中的文本
    def get_alert_text(self):
        alert = WebDriverWait(self.driver, 10).until(EC.alert_is_present())
        alert_text = alert.text
        alert.accept()
        return alert_text

    # 等待图片加载完成（指定图片）
    def await_img_loaded(self, loc):
        WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(loc))

    # 等待图片加载完成（所有图片）
    def await_imgs_loaded(self, loc):
        WebDriverWait(self.driver, 10).until(EC.presence_of_all_elements_located(loc))

    # 创建下拉框元素select对象
    def create_select(self, loc):
        dropdown = self.find_el(loc)
        select = Select(dropdown)
        return select